using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;

using FineUIPro;


namespace FineUIPro
{
    public static partial class FineUIProExtensions
    {

        /// <summary>
        /// 动态创建Grid结构，在 Page_Init事件里执行（不是Page_Load事件里）
        /// </summary>
        /// <param name="Grid1">The grid1.</param>
        /// <param name="dt">The dt.</param>
        /// <param name="headerDic">dt列名称获取对应HeaderText</param>
        public static void CreatGridStructByDataTable(this FineUIPro.Grid Grid1, DataTable dt,Dictionary<string,string> headerDic=null)
        {
            FineUIPro.BoundField bf;

            if (headerDic == null || headerDic.Count == 0)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    bf = new FineUIPro.BoundField();
                    bf.DataField = dt.Columns[i].Caption;
                    bf.DataFormatString = "{0}";
                    bf.HeaderText = dt.Columns[i].Caption;
                    Grid1.Columns.Add(bf);
                }
            }
            else
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    bf = new FineUIPro.BoundField();
                    bf.DataField = dt.Columns[i].Caption;
                    bf.DataFormatString = "{0}";
                    bf.HeaderText = headerDic[dt.Columns[i].Caption];
                    Grid1.Columns.Add(bf);
                }
            }
        }

        /// <summary>
        /// 生成扩展列表格html,别忘记加css
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="showHeader">是否显示表格头</param>
        /// <param name="headerDic">dt列名称获取对应HeaderText(需要设置showHeader为true)</param>
        /// <param name="columnWidths">列宽度集合(数量要和dt列数一致 否则异常)</param>
        /// <returns></returns>
        public static string GetExpanderHtml(DataTable dt, bool showHeader = true, Dictionary<string, string> headerDic = null, int[] columnWidths=null)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return string.Empty;
            }

            StringBuilder newLine = new StringBuilder();
            newLine.Append("<table class=\"mytable f-widget-header\">");
            //newLine.Append("<tr><td colspan=\String.Empty + dt.Columns.Count + "\" align=\"center\">" + dt.TableName + "</td></tr>");
            if (showHeader)
            {
                newLine.Append("<tr>");
                if (columnWidths != null && columnWidths.Length > 0)//有列宽度
                {
                    if (headerDic != null && headerDic.Count > 0)//映射列名
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            newLine.AppendFormat("<th class=\"f-widget-header\" style=\"width:{1}px\">{0}</th>", headerDic[dt.Columns[i].Caption], columnWidths[i]);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            newLine.AppendFormat("<th class=\"f-widget-header\" style=\"width:{1}px\">{0}</th>", dt.Columns[i].Caption, columnWidths[i]);
                        }
                    }
                }
                else
                {
                    if (headerDic != null && headerDic.Count > 0)//映射列名
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            newLine.AppendFormat("<th class=\"f-widget-header\">{0}</th>", headerDic[dt.Columns[i].Caption]);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            newLine.AppendFormat("<th class=\"f-widget-header\">{0}</th>", dt.Columns[i].Caption);
                        }
                    }
                }
                newLine.Append("</tr>");
            }

            if (columnWidths != null && columnWidths.Length > 0)//有列宽度
            {
                //首行添加宽度
                newLine.Append("<tr>");
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    newLine.AppendFormat("<td class=\"f-widget-content\" style=\"width:{1}px\">{0}</td>", dt.Rows[0][i],columnWidths[i]);
                }
                newLine.Append("</tr>");
                //其他行
                for (int j = 1; j < dt.Rows.Count; j++)
                {
                    newLine.Append("<tr>");
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        newLine.AppendFormat("<td class=\"f-widget-content\">{0}</td>", dt.Rows[j][i]);
                    }
                    newLine.Append("</tr>");
                }
            }
            else
            {
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    newLine.Append("<tr>");
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        newLine.AppendFormat("<td class=\"f-widget-content\">{0}</td>", dt.Rows[j][i]);
                    }
                    newLine.Append("</tr>");
                }
            }
            newLine.Append("</table>");
            return newLine.ToString();

            /* //所需的css，参考：https://pro.fineui.com/#/grid/grid_rowexpander_htmlgrid.aspx
             <style>
        .mytable {
            border-width: 1px;
            border-style: solid;
            border-collapse: separate;
            border-spacing: 0;
            border-bottom-width: 0;
            border-right-width: 0;
        }
            .mytable th,
            .mytable td {
                padding: 5px;
                text-align: left;
                border-bottom-width: 1px;
                border-bottom-style: solid;
                border-right-width: 1px;
                border-right-style: solid;
            }
    </style>
             */

            /* //调用示例
              lit.Text = FineUIProExtensions.GetExpanderHtml(GetDataTable(),
                headerDic:new Dictionary<string, string>(){{"id","主键"},{ "name", "内容"},{ "age", "年龄"}}, 
                columnWidths:new int[]{100,300,120});
             */
        }

        /// <summary>
        /// 获取选中行的主id
        /// </summary>
        /// <param name="grid">FineUIPro.Grid</param>
        /// <param name="keyNumIndex">第几个主键（从0开始）</param>
        /// <returns></returns>
        public static string GetDataKeysBySelectedRow(this FineUIPro.Grid grid, int keyNumIndex = 0)
        {
            //需要正确设置grid DataKeyNames主键列名
            int[] selections = grid.SelectedRowIndexArray;//获取选中行
            if (selections.Length == 0)
            {
                return string.Empty;
            }

            StringBuilder sb = new StringBuilder();
            foreach (int rowIndex in selections)
            {
                sb.Append("," + int.Parse(grid.DataKeys[rowIndex][keyNumIndex].ToString()));
            }

            return sb.ToString().Substring(1);
        }

        /// <summary>
        /// 获取选中行的主id
        /// </summary>
        /// <param name="grid">FineUIPro.Grid</param>
        /// <param name="keyNumIndex">第几个主键（从0开始）</param>
        /// <returns></returns>
        public static List<int> GetDataKeysListBySelectedRow(this FineUIPro.Grid grid, int keyNumIndex = 0)
        {
            //需要正确设置grid DataKeyNames主键列名
            int[] selections = grid.SelectedRowIndexArray;//获取选中行
            if (selections.Length == 0)
            {
                return null;
            }

            List<int> list = new List<int>();
            foreach (int rowIndex in selections)
            {
                list.Add(int.Parse(grid.DataKeys[rowIndex][keyNumIndex].ToString()));//获取每行第keyNumIndex个主键
            }
            return list;
        }


        public static List<TGridViewModel> BindFineuiBySqlSugar<TGridViewModel>(this FineUIPro.Grid grid, SqlSugar.ISugarQueryable<TGridViewModel> queryable)
        {
            int recordCount = 0;

            List<TGridViewModel> data = queryable.ToPageList(grid.PageIndex, grid.PageSize, ref recordCount);

            grid.RecordCount = recordCount;
            grid.DataSource = data;
            grid.DataBind();
            return data;
        }

        

    }
}

